package com.util.xml.parse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Repository;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.util.common.FilePath;

@Repository("xmlParseImp")
public class XMLParseImp implements XMLParse {
	private String fileAddress;

	public String getFileAddress() {
		return fileAddress;
	}

	public void setFileAddress(String fileAddress) {
		this.fileAddress = fileAddress;
	}

	/**
     * 获得根节点元素
     * @return
     */
    public Element getRootElement(){
	    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		Element root = null;
		try{
			String path = FilePath.getAbsolutePathWithClass() + this.fileAddress;
			DocumentBuilder db = factory.newDocumentBuilder();
		    Document xmldoc = db.parse(new File(path));
			root = xmldoc.getDocumentElement();
		} catch (ParserConfigurationException e){
		    e.printStackTrace();
		} catch (SAXException e){
		    e.printStackTrace();
		} catch (IOException e){
		    e.printStackTrace();
		}
		return root;
    }
    
    /**
     * 保存XML文档
     * @param element
     * @param filePath
     * @throws IOException
     */
	public void saveXML(Element element, String filePath){
		this.setFileAddress(filePath);
		saveXML(element);
	}
	
    /**
     * 保存XML文档
     * @param element
     * @throws IOException
     */
	public void saveXML(Element element){
		String path = this.getClass().getResource("/").getPath()+this.fileAddress;
		System.out.println(path);
		FileOutputStream outStream = null;
		Transformer trans = null;
		try {
			outStream = new FileOutputStream( new File(path));
			trans = TransformerFactory.newInstance().newTransformer();
			trans.transform(new DOMSource(element), new StreamResult(outStream));
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(outStream);
		}
    }

    /**
     * 获得node节点下elementName元素的文本内容，
     * 无elementName则返回为""
     * @param node
     * @param elementName
     * @return
     */
    public String getTextContent(Element element, String elementName){
    	String textContent = "";
    	if(element != null){
    		NodeList nodeList = element.getElementsByTagName(elementName);
    		if(nodeList != null && nodeList.getLength() > 0){
    			Node childNode = nodeList.item(0);
    			textContent = childNode.getTextContent();
    		}
    	}
    	if(textContent == null){
    		textContent = "";
    	}
    	return textContent;
    }
    
    /*
	  * 根据节点名和节点属性
	  * 获得各个节点的value属性值，或者是value节点的text节点
	  */
    public static String getValue(String nodeName,String attrKey,String attrValue,Element allElement){
	   	Element nodeNameElement = null;
	   	//获得所有以nodeName名的节点
	   	NodeList nodeList = allElement.getElementsByTagName(nodeName);
			for(int i = 0;i < nodeList.getLength();i++){
				nodeNameElement = (Element)nodeList.item(i);
				NodeList valueNodeList = nodeNameElement.getChildNodes();
				if(nodeNameElement.getAttribute(attrKey).equals(attrValue)){
					if(nodeNameElement.hasAttribute("value")){
						//节点存在value属性，则返回value属性值
						return nodeNameElement.getAttribute("value");
					}else if(valueNodeList.getLength() > 0){
						//节点下存在value节点，并且是一级之节点，则输出value节点的Text内容
						for(int j = 0;j < valueNodeList.getLength();j++ ){
							if("value".equals(valueNodeList.item(j).getNodeName())){
								return valueNodeList.item(j).getTextContent();
							}
						}
					}
				}
			}
					
	   	return null;
   }

	@Override
	public String getValueAttrOrElem(Element element, String elementName) {
		String value = null;
	   	NodeList nodeList = element.getElementsByTagName(elementName);
	   	if(nodeList != null && nodeList.getLength() > 0){
	   		Element nodeElement = (Element) nodeList.item(0);
   			value = nodeElement.getAttribute("value");
   			NodeList stempList = nodeElement.getElementsByTagName("value");
   			if(stempList != null && stempList.getLength() > 0){
   				value = stempList.item(0).getTextContent();
   			}
	   	}
	   	return value;
	}

}
